package com.junjie.blibli.exception;

import com.junjie.blibli.Exception.http.ConditionException;
import com.junjie.blibli.Exception.http.HttpException;
import com.junjie.blibli.config.CodeConfiguration;
import com.junjie.blibli.result.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
//这个注解的意思是这个拦截器的优先级是最高的
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
    @Autowired
    private CodeConfiguration codeConfiguration;

    @ExceptionHandler(value = Exception.class)
    //但是在我们返回统一返回类后，发现虽然返回的信息状态码是9999，但是请求上的状态码是200？
    //这时候就需要用到使用注解来修改请求上的状态了，如下图，一键修改状态码为500
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResponse<String> commonExceptionHandler(HttpServletRequest request,Exception e){
        String errorMessage = e.getMessage();
        if(e instanceof ConditionException){
            String errorCode = ((ConditionException) e).getCode();
            return new JsonResponse<>(errorCode,errorMessage);
        }else{
            return new JsonResponse<>("500",errorMessage);
        }
    }

    @ExceptionHandler(value = HttpException.class)
    public ResponseEntity<JsonResponse<Object>> handlerHttpException(HttpServletRequest request,HttpException e){
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        JsonResponse<Object> message = new JsonResponse<>(e.getCode() + "", codeConfiguration.getMessage(e.getCode()));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());
        ResponseEntity<JsonResponse<Object>> responseEntity = new ResponseEntity<>(message,httpHeaders,httpStatus);
        return responseEntity;
    }

}
